package com.moshang.blog.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moshang.blog.controller.base.BaseController;
import com.moshang.blog.core.utils.StringUtils;
import com.moshang.blog.entity.*;
import com.moshang.blog.service.*;
import com.moshang.blog.core.utils.PageUtil;
import com.moshang.blog.core.utils.RestResponse;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @program: blog
 * @description: 前台博客控制器类
 * @author: moshang
 * @create: 2018-12-13 10:03
 **/
@Controller
@RequestMapping("/blog")
public class BlogController extends BaseController {

    @Autowired
    private TbArticleInfoService tbArticleInfoService;
    @Autowired
    private TbMessageService tbMessageService;
    @Autowired
    private TbSortService tbSortService;
    @Autowired
    private ThirdLoginUserService thirdLoginUserService;
    @Autowired
    private SysRescourceService rescourceService;
    @Autowired
    private SysDictService sysDictService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;
    public static final String SCORE_RANK = "score_rank";

    /**
     *  空地址请求
     * @return
     */
    @GetMapping(value = {"","/toHome"})
    public String index(Model model,@RequestParam(value = "page",defaultValue = "1",required = false)Integer page,
            @RequestParam(value = "limit",defaultValue = "10",required = false)Integer limit,HttpSession httpSession) {
//       if ()
//        ThreadContext.remove(ThreadContext.SUBJECT_KEY);
        PageUtil<TbArticleInfo> pageUtil = new PageUtil<>();
        //查询所有置顶的文章
        QueryWrapper<TbArticleInfo> entityWrapper=new QueryWrapper<>();
        entityWrapper.eq("is_top",1);
        entityWrapper.eq("status",1);
        entityWrapper.eq("is_activited",0);
        entityWrapper.orderByDesc("create_time");
        IPage<TbArticleInfo> articleInfoPage=tbArticleInfoService.page(new Page<>(page,limit),entityWrapper);
        pageUtil.setCount((int) articleInfoPage.getTotal());
        pageUtil.setData(articleInfoPage.getRecords());
        pageUtil.setPage(page);
        Integer totalPage=(pageUtil.getCount()-1)/limit;
        pageUtil.setTotalPage(totalPage);
        model.addAttribute("pageUtil",pageUtil);
        //查询最新推荐的五篇文章
        List<TbArticleInfo> isRecommends=tbArticleInfoService.findByIsRecommend();
        Set<String> strings = redisTemplate.opsForZSet().reverseRange(SCORE_RANK, 0, 3);
        model.addAttribute("isRecommends",isRecommends);
        //查询最新的五个资源
        List<Rescource> rescources=rescourceService.findByLately();
        model.addAttribute("rescources",rescources);
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //查询最近访客
       List<ThirdLoginUser> list= thirdLoginUserService.findByStatus(2);
        model.addAttribute("list",list);
        return "web/index";
    }
    /**
     *  空地址请求
     * @return
     */
    @PostMapping(value ="/list")
    @ResponseBody
    public RestResponse list(Model model,@RequestParam(value = "page",defaultValue = "1",required = false)Integer page,
                        @RequestParam(value = "limit",defaultValue = "10",required = false)Integer limit,HttpSession httpSession) {
        RestResponse restResponse=new RestResponse();
        PageUtil<TbArticleInfo> pageUtil = new PageUtil<>();
        //查询所有置顶的文章
        QueryWrapper<TbArticleInfo> entityWrapper=new QueryWrapper<>();
        entityWrapper.eq("is_top",1);
        entityWrapper.eq("status",1);
        entityWrapper.eq("is_activited",0);
        entityWrapper.orderByDesc("create_time");
        IPage<TbArticleInfo> articleInfoPage=tbArticleInfoService.page(new Page<>(page,limit),entityWrapper);
        pageUtil.setCount((int) articleInfoPage.getTotal());
        pageUtil.setData(articleInfoPage.getRecords());
        Integer totalPage=(pageUtil.getCount()+limit-1)/limit;
        pageUtil.setTotalPage(totalPage);
        pageUtil.setPage(page);
        restResponse.setData(pageUtil);
        return restResponse;
    }
    /**
     *  进入文章专栏
     * @return
     */
    @GetMapping(value = "toArticle")
    public String toArticle(Model model,@RequestParam(value = "page",defaultValue = "1",required = false)Integer page,
    @RequestParam(value = "limit",defaultValue = "10",required = false)Integer limit,HttpSession httpSession) {
       //查询所有发布的文章
        PageUtil<TbArticleInfo> pageUtil = new PageUtil<>();
        //查询所有置顶的文章
        QueryWrapper<TbArticleInfo> entityWrapper=new QueryWrapper<>();
        entityWrapper.eq("status",1);
        entityWrapper.eq("is_activited",0);
        entityWrapper.orderByDesc("create_time");
        IPage<TbArticleInfo> articleInfoPage=tbArticleInfoService.page(new Page<>(page,limit),entityWrapper);
        pageUtil.setCount((int) articleInfoPage.getTotal());
        pageUtil.setData(articleInfoPage.getRecords());
        pageUtil.setPage(page);
        model.addAttribute("pageUtil",pageUtil);
        //查询分类
        model.addAttribute("sortList",getSorts());
        //查询标签
        model.addAttribute("labelList",getLabels());
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //查询最新推荐的五篇文章
        List<TbArticleInfo> isRecommends=tbArticleInfoService.findByIsRecommend();
        model.addAttribute("isRecommends",isRecommends);
        return "web/article";
    }
    /**
     *  模糊搜索文章
     * @return
     */
    @GetMapping(value = "toFindArticle")
    public String toFindArticle(Model model, @RequestParam(value = "page",defaultValue = "1",required = false)Integer page,
                                @RequestParam(value = "limit",defaultValue = "10",required = false)Integer limit, HttpServletRequest request,HttpSession httpSession) {
        //查询所有发布的文章
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        PageUtil<TbArticleInfo> pageUtil = new PageUtil<>();
        String key="";
        //查询所有置顶的文章
        QueryWrapper<TbArticleInfo> entityWrapper=new QueryWrapper<>();
        if (!map.isEmpty()){
            key = (String) map.get("keywords");
         entityWrapper.like("title",key).or().like("content",key).or().like("introduction",key);
        }
        entityWrapper.eq("is_activited",0);
        entityWrapper.orderByDesc("create_time");
        IPage<TbArticleInfo> articleInfoPage=tbArticleInfoService.page(new Page<>(page,limit),entityWrapper);
        pageUtil.setCount((int) articleInfoPage.getTotal());
        pageUtil.setData(articleInfoPage.getRecords());
        pageUtil.setPage(page);
        model.addAttribute("pageUtil",pageUtil);
        //查询分类
        model.addAttribute("sortList",getSorts());
        //查询标签
        model.addAttribute("labelList",getLabels());
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //查询最新推荐的五篇文章
        List<TbArticleInfo> isRecommends=tbArticleInfoService.findByIsRecommend();
        model.addAttribute("isRecommends",isRecommends);
        model.addAttribute("key",key);
        return "web/search";
    }
    /**
     * 查询分类下的文章
     * @return
     */
    @GetMapping(value = "toSortArticle")
    public String toSortArticle(Model model,@RequestParam(value = "page",defaultValue = "1",required = false)Integer page,
                            @RequestParam(value = "limit",defaultValue = "10",required = false)Integer limit,@RequestParam("sortId")Integer sortId,HttpSession httpSession) {
        //查询此分类下所有发布的文章
        PageUtil<TbArticleInfo> pageUtil = new PageUtil<>();
        //查询所有置顶的文章
        QueryWrapper<TbArticleInfo> entityWrapper=new QueryWrapper<>();
        entityWrapper.eq("sort_id",sortId);
        entityWrapper.eq("status",1);
        entityWrapper.eq("is_activited",0);
        entityWrapper.orderByDesc("create_time");
        IPage<TbArticleInfo> articleInfoPage=tbArticleInfoService.page(new Page<>(page,limit),entityWrapper);
        pageUtil.setCount((int) articleInfoPage.getTotal());
        pageUtil.setData(articleInfoPage.getRecords());
        pageUtil.setPage(page);
        model.addAttribute("pageUtil",pageUtil);
        TbSort tbSort=tbSortService.getById(sortId);
        //查询分类
        model.addAttribute("sortList",getSorts());
        model.addAttribute("tbSort",tbSort);
        //查询标签
        model.addAttribute("labelList",getLabels());
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //查询最新推荐的五篇文章
        List<TbArticleInfo> isRecommends=tbArticleInfoService.findByIsRecommend();
        model.addAttribute("isRecommends",isRecommends);
        return "web/sortArticle";
    }
    /**
     * 查询标签下的文章
     * @return
     */
    @GetMapping(value = "toLableArticle")
    public String toLableArticle(Model model,@RequestParam(value = "page",defaultValue = "1",required = false)Integer page,
                                @RequestParam(value = "limit",defaultValue = "10",required = false)Integer limit,@RequestParam("label")String label,HttpSession httpSession) {
        //查询此分类下所有发布的文章
        PageUtil<TbArticleInfo> pageUtil = new PageUtil<>();
        //查询所有置顶的文章
        QueryWrapper<TbArticleInfo> entityWrapper=new QueryWrapper<>();
        entityWrapper.eq("label",label);
        entityWrapper.eq("status",1);
        entityWrapper.eq("is_activited",0);
        entityWrapper.orderByDesc("create_time");
        IPage<TbArticleInfo> articleInfoPage=tbArticleInfoService.page(new Page<>(page,limit),entityWrapper);
        pageUtil.setCount((int) articleInfoPage.getTotal());
        pageUtil.setData(articleInfoPage.getRecords());
        pageUtil.setPage(page);
        model.addAttribute("pageUtil",pageUtil);
        //查询分类
        model.addAttribute("sortList",getSorts());
        //查询标签
        model.addAttribute("labelList",getLabels());
        model.addAttribute("label",label);
        //model.addAttribute("tbSort",tbSort);
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //查询最新推荐的五篇文章
        List<TbArticleInfo> isRecommends=tbArticleInfoService.findByIsRecommend();
        model.addAttribute("isRecommends",isRecommends);
        return "web/labelArticle";
    }
    /**
     *  进入文章详情
     * @return
     */
    @GetMapping(value = "toDetail")
    public String toDetail(@RequestParam("id")Integer id, Model model, HttpSession httpSession) {
        //查询文章
        TbArticleInfo tbArticleInfo=tbArticleInfoService.findById(id);
        Integer likeCount=redisService.findLikedCount(id);
        tbArticleInfo.setSupport(likeCount);
        redisTemplate.opsForZSet().incrementScore(SCORE_RANK, String.valueOf(id), 1);
        Double ssid=redisTemplate.opsForZSet().score(SCORE_RANK, String.valueOf(id));
        System.out.println(ssid);
        tbArticleInfo.setTraffic(tbArticleInfo.getTraffic()+1);
        tbArticleInfoService.updateById(tbArticleInfo);
        //查看评论总数
        Integer count=tbMessageService.findCount(id);
        model.addAttribute("tbArticleInfo",tbArticleInfo);
        model.addAttribute("count",count);
        //查询相似文章
        List<TbArticleInfo> nearlist=tbArticleInfoService.findNear(id,tbArticleInfo.getSortId());
        model.addAttribute("nearlist",nearlist);
        //查询分类
        model.addAttribute("sortList",getSorts());
        //查询标签
        model.addAttribute("labelList",getLabels());
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //访问量加1
        return "web/detail";
    }
    /**
     *  查询评论总数
     * @return
     */
    @GetMapping(value = "findCount")
    @ApiOperation(value = "/findCount", httpMethod = "GET", notes = "查询评论")
    @ResponseBody
    public Integer findList(@RequestParam("id")Integer id) {
        //根据文章Id查询评论
        QueryWrapper<TbMessage> entityWrapper=new QueryWrapper<>();
        entityWrapper.eq("is_activited",0);
        entityWrapper.eq("article_id",id);
        entityWrapper.eq("type",1);
        Integer count=tbMessageService.count(entityWrapper);
        return count;
    }
    /**
     *  查询评论
     * @return
     */
    @GetMapping(value = "findList")
    @ApiOperation(value = "/findList", httpMethod = "GET", notes = "查询评论")
    @ResponseBody
    public RestResponse findList(@RequestParam(value = "page",required = false)Integer page,
                                      @RequestParam(value = "limit",required = false,defaultValue = "10")Integer limit, @RequestParam("id")Integer id, HttpSession httpSession) {
        PageUtil<TbMessage> pageUtil = new PageUtil<>();
        RestResponse restResponse=new RestResponse();

        //根据文章Id查询评论
        QueryWrapper<TbMessage> entityWrapper=new QueryWrapper<>();
        entityWrapper.eq("is_activited",0);
        entityWrapper.eq("article_id",id);
        entityWrapper.eq("type",TbMessage.COMMENT);
        entityWrapper.eq("parent_id",-1);
        entityWrapper.orderByDesc("create_time");
        IPage<TbMessage> messageList=tbMessageService.page(new Page<>(page,limit),entityWrapper);
        if (messageList.getTotal()>0){
             tbMessageService.selectMessages(messageList.getRecords());
        }
        pageUtil.setCount((int) messageList.getTotal());
        pageUtil.setData(messageList.getRecords());
        pageUtil.setPage(page);
        Integer totalPage=(pageUtil.getCount()+limit-1)/limit;
        pageUtil.setTotalPage(totalPage);
        restResponse.setCode("200");
        restResponse.setData(pageUtil);
        return restResponse;
    }
    /**
     *  查询留言
     * @return
     */
    @GetMapping(value = "findMessage")
    @ApiOperation(value = "/findMessage", httpMethod = "GET", notes = "查询留言")
    @ResponseBody
    public RestResponse findMessage(@RequestParam(value = "page",required = false)Integer page,
                                        @RequestParam(value = "limit",required = false,defaultValue = "10")Integer limit) {
        PageUtil<TbMessage> pageUtil=new PageUtil<>();
        RestResponse restResponse=new RestResponse();
        QueryWrapper<TbMessage> entityWrapper=new QueryWrapper<>();
        entityWrapper.eq("is_activited",0);
        entityWrapper.eq("parent_id",-1);
        entityWrapper.eq("type",TbMessage.MESSAGE);
        entityWrapper.orderByDesc("create_time");
        IPage<TbMessage> messageList= tbMessageService.page(new Page<>(page,limit),entityWrapper);
        if (messageList.getTotal()>0) {
            tbMessageService.selectMessages(messageList.getRecords());
        }
        pageUtil.setCount((int) messageList.getTotal());
        pageUtil.setData(messageList.getRecords());
        pageUtil.setPage(page);
        Integer totalPage=(pageUtil.getCount()+limit-1)/limit;
        pageUtil.setTotalPage(totalPage);
        restResponse.setCode("200");
        restResponse.setData(pageUtil);
        return restResponse;
    }
    /**
     *  进入资源专栏
     * @return
     */
    @GetMapping(value = "toResource")
    public String toResource(HttpSession httpSession,Model model,@RequestParam(value = "page",defaultValue = "1",required = false)Integer page,
                             @RequestParam(value = "limit",defaultValue = "10",required = false)Integer limit,@RequestParam(value = "categoryName",defaultValue = "",required = false)String categoryName) {
        PageUtil<Rescource> pageUtil = new PageUtil<>();
        QueryWrapper<Rescource> entityWrapper=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(categoryName)){
          SysDict sysDict=sysDictService.selectByCondition("文件分类",categoryName);
          if (sysDict!=null){
              entityWrapper.eq("category",sysDict.getId());
          }
        }

        entityWrapper.orderByDesc("create_time");
        IPage<Rescource> rescourcePage=rescourceService.page(new Page<>(page,limit),entityWrapper);
        pageUtil.setCount((int) rescourcePage.getTotal());
        for (Rescource rescource:rescourcePage.getRecords()){
            if (rescource.getCategory()!=null) {
                SysDict sysDict = sysDictService.getById(rescource.getCategory());
                rescource.setCategoryName(sysDict.getValue());
            }else {
                rescource.setCategoryName("图片");
            }
        }
        pageUtil.setData(rescourcePage.getRecords());
        pageUtil.setPage(page);
        model.addAttribute("pageUtil",pageUtil);
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //查询所有文章
        return "web/resource";
    }
    /**
     *  点点滴滴
     * @return
     */
    @GetMapping(value = "toTimeline")
    public String toTimeline(HttpSession httpSession,Model model) {
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //查询所有文章
        return "web/timeline";
    }
    /**
     *  点赞
     * @return
     */
    @GetMapping(value = "support")
    @ResponseBody
    public RestResponse support(@RequestParam("articleId")Integer articleId,@RequestParam("userId")Integer userId) {
        TbArticleInfo tbArticleInfo=tbArticleInfoService.findById(articleId);
        if (tbArticleInfo!=null){
            return tbArticleInfoService.updateInfo(tbArticleInfo.getId(),userId);

        }
        return null;
    }
    /**
     *  关于本站
     * @return
     */
    @GetMapping(value = "about")
    public String about(HttpSession httpSession,Model model) {
        //查找留言总数
        Integer count=tbMessageService.findMessage(TbMessage.MESSAGE);
        model.addAttribute("count",count);
        if(httpSession!=null){
            ThirdLoginUser thirdLoginUser= (ThirdLoginUser) httpSession.getAttribute("thirdLoginUser");
            if (thirdLoginUser!=null){
                model.addAttribute("thirdLoginUser",thirdLoginUser);
            }
        }
        //查询所有文章
        return "web/about";
    }
}
